package com.xjgc.common.utils;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.xjgc.model.entity.general.*;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class MapperUtils {

    private Class<?> aClass;
    private String tableName;
    private String[] primaryKeys;
    private String filePath;
    private int position;
    private File file;

    public MapperUtils() {

    }

    public MapperUtils(String tableName, String... primaryKeys) throws ClassNotFoundException, UnsupportedEncodingException, URISyntaxException {
        this.aClass = Class.forName(getEntityStr(tableName));
        this.tableName = tableName;
        this.primaryKeys = primaryKeys;
        file = new File("bjxj-imis-module-msi\\src\\main\\java\\com\\xjgc\\dao\\"+packageName+"\\mapperxml\\" + this.aClass.getSimpleName() + "Mapper.xml");
        this.filePath = file.getAbsolutePath();
        this.filePath = java.net.URLDecoder.decode(this.filePath, "utf-8");
}

    private void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    private void setTableName(String tableName) {
        this.tableName = tableName;
    }

    private void setClass(String className) throws ClassNotFoundException {
        aClass = Class.forName(className);
    }

    public String getBatchSql() throws ClassNotFoundException, IOException {
        //判断文件是否存在
        //System.out.println(filePath);
        if (!(file.exists() && file.isFile())) {
            System.out.println("文件不存在  ~ ");
            return "mapper文件不存在  ~ ";
        }
        List<String> lines = Files.readAllLines(Paths.get(file.getPath()), StandardCharsets.UTF_8);
        position = lines.size() - 1;
        //判断position是否合法
        if ((position < 0) || (position > file.length())) {
            System.out.println("mapper文件sql语句insertBatch、deleteBatch中position不合法 ~ ");
            return "mapper文件sql语句insertBatch、deleteBatch中position不合法 ~ ";
        }
        lines.add(position, getBatchInsertSql() + "\n" + getBatchDeleteSql());
        Files.write(Paths.get(filePath), lines, StandardCharsets.UTF_8);

//        StringBuilder res = new StringBuilder().append("----------mapper文件sql语句------------\n");
//        System.out.println(getBatchInsertSql());
//        System.out.println(getBatchDeleteSql());
//        res.append("\n-------------mapper类方法---------------\n");
//        res.append("void insertBatch(List<" + aClass.getSimpleName() + "> entities);\n");
//        res.append("void deleteBatch(List<" + aClass.getSimpleName() + "> entities);");
        System.out.println("mapper文件sql语句insertBatch、deleteBatch添加成功");
        return "mapper文件sql语句insertBatch、deleteBatch添加成功";
    }

    /**
     * @return
     * @throws ClassNotFoundException
     */
    private String getBatchInsertSql() throws ClassNotFoundException {

        StringBuilder res = new StringBuilder().append("\t<insert id=\"insertBatch\" parameterType=\"List\">\n" +
                "\t\t insert into " + tableName + "(");
        List<String> fieldsName = getFieldsName();
        for (String fieldName : fieldsName) {
            res.append("\"" + fieldName + "\",");
        }
        res.deleteCharAt(res.length() - 1);
        res.append(") VALUES\n\t\t<foreach collection=\"list\" item=\"entity\" separator=\",\">\n\t\t\t(");

        for (String fieldName : fieldsName) {
            res.append("#{entity." + getFieldStr(fieldName) + "},");
        }
        res.deleteCharAt(res.length() - 1);
        res.append(")\n\t\t</foreach>\n\t</insert>");

        return res.toString();
    }

    /**
     * @return
     * @throws ClassNotFoundException
     */
    private String getBatchDeleteSql() throws ClassNotFoundException {

        StringBuilder res = new StringBuilder().append("\t<delete id=\"deleteBatch\" parameterType=\"List\">\n" +
                "\t\t delete from " + tableName + " where (");

        for (String primaryKey : primaryKeys) {
            res.append("\"" + primaryKey + "\",");
        }
        res.deleteCharAt(res.length() - 1);
        res.append(") in(\n\t\t<foreach collection=\"list\" item=\"entity\" separator=\",\">\n\t\t\t(");

        for (String primaryKey : primaryKeys) {

            res.append("#{entity." + getFieldStr(primaryKey) + "},");
        }
        res.deleteCharAt(res.length() - 1);
        res.append(")\n\t\t</foreach>)\n\t</delete>");


        return res.toString();
    }

    private List<String> getFieldsName() {
        ArrayList<String> fieldsName = new ArrayList<>();
        Field[] fields = aClass.getDeclaredFields();
        for (int i = 1; i < fields.length; i++) {
            JsonProperty annotation = fields[i].getAnnotation(JsonProperty.class);
            if (annotation==null){
                continue;
            }
            fieldsName.add(annotation.value());

        }
        return fieldsName;
    }

    private String getFieldStr(String fieldName) {
        String[] split = fieldName.split("_");
        String res2 = "", res1 = StringUtils.lowerCase(split[0]);
        if (split.length > 1) {
            for (int i = 1; i < split.length; i++) {
                res2 += StringUtils.capitalize(StringUtils.lowerCase(split[i]));
            }
        }
        return res1 + res2;
    }

    private String getEntityStr(String entityName) {
        String[] split = entityName.split("_");
        String res = "com.xjgc.model.entity."+packageName+".";
        for (int i = 0; i < split.length; i++) {
            res += StringUtils.capitalize(StringUtils.lowerCase(split[i]));
        }
        return res;
    }

    private static String[] tableNames_MAIN = {"zxj_zsdstr015"};
    private static String[][] primaryKeys_MAIN = { {"VBELN"}};
    private static String packageName="general";

    public static void main(String[] args) throws ClassNotFoundException, IOException, URISyntaxException {
//        new MapperUtils("zxj_zsdstr018", "BSSNU","POSN").getBatchSql();
//        System.out.println(ZxjZsdstr016.class.getTypeName());
        int i = 0;
        for (String tableName : tableNames_MAIN) {
            if (i <= primaryKeys_MAIN.length - 1) {
                new MapperUtils(
                        tableName,
                        primaryKeys_MAIN[i])
                        .getBatchSql();
                i++;
            }
        }
    }

}
